package handlers

import (
	"github.com/gin-gonic/gin"
	"shop-ease/models"
	"shop-ease/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}

	if user.Password != pkg.Md5str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	}

	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})

}
